<?php


namespace App\Http\Controllers\Wechat;


use App\Models\AuthenticLog;
use App\Models\Config;
use App\Models\GoodsCustomRent;
use App\Models\GoodsSpec;
use App\Models\ShopUser;
use App\Models\WechatMember;
use App\Models\Goods;
use App\Models\Category;
use App\Models\Order;
use App\Models\ShopSms;
use App\Models\GoodsSetmeal;
use App\Models\OrderRate;
use App\Models\OrderLease;
use App\Services\CommonService;
use App\Services\EsignService;
use App\Services\AlipayService;
use App\Services\EsignV3Service;
use App\Services\IdCardService;
use App\Services\OrderService;
use App\Services\GoodsService;
use App\Services\WechatService;
use Illuminate\Http\Request;

class AuthenticController extends BaseController
// class AuthenticController
{
    /**
     * 获取实名认证信息
     * @return false|string
     */
    public function getPersonAuth(){
        $cert_no = !empty($this->member['cert_no']) ? $this->member['cert_no'] : '';
        $authenticLog = AuthenticLog::where(['cert_no'=>$cert_no])->select('status')->orderBy('order_id','desc')->first();
        $data = [
            'certName'=>!empty($this->member['cert_name']) ? $this->member['cert_name'] : '',
            'certNo'=>!empty($this->member['cert_no']) ? $this->member['cert_no'] : '',
            'cardFront'=>!empty($this->member['idcard_front']) ? $this->member['idcard_front'] : '',
            'cardBack'=>!empty($this->member['idcard_back']) ? $this->member['idcard_back'] : '',
            'is_auth'=>$authenticLog?$authenticLog['status']:0
        ];
        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'获取成功',$data);
    }

    /**
     * 实人认证
     * @param Request $request
     * @return false|string
     * @throws \Exception
     */
    public function realPersonAuth(Request $request){
        // dd(1);
        $certName = $request->input('certName');
        $certNo = $request->input('certNo')?$request->input('certNo'):'';
        $orderId = $request->input('orderId')?$request->input('orderId'):'';
        $cardFront = $request->input('cardFront');
        $cardBack = $request->input('cardBack');
        $type = $request->input('type')?$request->input('type'):'1';



        $goods_id = $request->input('gooddsId')?$request->input('gooddsId'):'';

//        if(!$certName || !$certNo || !$cardFront || !$cardBack || !$orderId){
//            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'参数错误');
//        }
        if (!check_passportid($certNo)) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'身份证号无效');
        }

        if($certNo){
            $age=getAgeByID($certNo);
            $config=Config::settingDetail();
            if($age<$config['min_age']||$age>$config['max_age']){
                return ['status' => CommonService::HTTP_CODE_FAIL, 'msg' => '您年龄不符合要求', 'data' => []];//，需要大于18岁小于40岁
            }
        }

//        $res=IdCardService::build(['infoImg'=>imgToBase64('https://img.qianbaozuji.com/'.$cardFront),'emblemImg'=>imgToBase64('https://img.qianbaozuji.com/'.$cardBack)]);
//
//        if($res['curlRes']['code']!=0){
//            return ReturnMsg(CommonService::HTTP_CODE_FAIL,$res['curlRes']['message']);
//        }
//        if($res['curlRes']['data']['name']!=$certName){
//            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'填写的姓名与身份证不一致');
//        }
//        if($res['curlRes']['data']['idNo']!=$certNo){
//            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'填写的身份证号与身份证不一致');
//        }
//        if($res['curlRes']['data']['validityPeriod']){
//            $validityPeriod=explode('-',$res['curlRes']['data']['validityPeriod']);
//            $dateString = $validityPeriod[1];
//            $dateArray = explode('.', $dateString); // 将日期分割为数组
//            $correctDateString = implode('-', $dateArray); // 将数组元素用 - 连接，得到正确的日期格式
//            $timestamp = strtotime($correctDateString); // 转换为时间戳
//            if($timestamp<time()){
//                return ReturnMsg(CommonService::HTTP_CODE_FAIL,'身份证有效期已过期,请重新提交');
//            }
//        }



        // $this->member['id'] = 45226;
        // echo '<pre>';
        // print_r($this->member);
        // dd(1);
        $member = WechatMember::where(['id'=>$this->member['id']])
                ->select(
                    "esign_user_id",'id','mobile','esign_seal_id'
                    )
                ->first();
        //创建个人账号
        if(empty($member['esign_user_id'])){
            $data1 = EsignV3Service::addPersonAccountID($certName,$certNo,$member['mobile']);
            if(!empty($data1['accountId'])){
                $esign_user_id = $data1['accountId'];
                WechatMember::where(['id'=>$this->member['id']])->update(['esign_user_id'=>$esign_user_id]);
            }else{
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '合同签署账号创建失败');
            }
        }else{
            $esign_user_id = EsignV3Service::updateAccounts($member['esign_user_id'],$certNo,$certName);
        }

        //创建个人印章
        if(empty($member['esign_seal_id'])){

            $seal_id = EsignV3Service::personaltemplate($esign_user_id);

            if($seal_id){
                WechatMember::where(['id'=>$this->member['id']])->update(['esign_seal_id'=>$seal_id]);
            }else{
                $flag = false;
            }
        }

        $response = EsignV3Service::checkWechatWebFaceAuth($esign_user_id,$certName,$certNo,$type,2);//e签宝实人认证


        // dd($response);
        if($response){
            if($orderId){
                $sign_status=Order::where('id',$orderId)->value('sign_status');
                if($sign_status==2){
                    return ReturnMsg(CommonService::HTTP_CODE_FAIL,'合同已签署，请勿重复签署');
                }
                $authenticLog = AuthenticLog::where(['order_id'=>$orderId])->select('id')->first();

            }else{
                $authenticLog = AuthenticLog::where(['cert_no'=>$certNo])->select('id')->orderBy('id','desc')->first();
            }


            $authenticLog = obToArray($authenticLog);
            //更改实名认证
            $resData = $response;
            $data = [
                'cert_no'=>$certNo,
                'cert_name'=>$certName,
                //更改实名认证
                'certify_id'=>$resData['flowId'],
                'idcard_front'=>$cardFront,
                'idcard_back'=>$cardBack,
                'request'=>json_encode($response),
            ];
            //更新用户信息
            WechatMember::where(['id'=>$this->member['id']])->update([
                'cert_no'=>$certNo,
                'cert_name'=>$certName,
                'idcard_front'=>$cardFront,
                'idcard_back'=>$cardBack,
            ]);
            if($orderId){
                $data['order_id'] = $orderId;
                Order::where('id',$orderId)->update(['face_flow_id'=>$resData['flowId']]);
            }
            if($authenticLog){
                AuthenticLog::where(['id'=>$authenticLog['id']])->update($data);
            }else{
                AuthenticLog::insert($data);
            }


            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'唤起实名认证成功',[
                //更改实名认证
                "url" => $resData['originalUrl'],
                "faceToken" => $resData['faceToken'],
                "flowId" => $resData['flowId'],
                "user_id" => $member['id']
            ]);
        }
        return ReturnMsg(CommonService::HTTP_CODE_FAIL,'唤起实名认证失败');
    }
    /**
     * e签宝微信人脸识别成功回调
     */
    public function faceAuthNotice(Request $request){

        $request_data = $request->all();
        EsignV3Service::addLog('e签宝人脸识别回调微信','',$request_data);

        $flow_id = $request_data['faceFlowId'];
        $type=$request_data['type'];

        $res=IdCardService::faceCheck($flow_id);
        if($flow_id&&$res['curlRes']['data']['status']=='SUCCESS'){
            $log = AuthenticLog::where(['certify_id'=>$flow_id])->orderBy('id','desc')->select('id','order_id','cert_no','cert_name','idcard_front','idcard_back')->first();
            $log = obToArray($log);
            $order_data = Order::where('id',$log['order_id'])->select('id','uid','trade_no','mobile','seller_id','realname')->first();
            if($log&&$order_data){
                $update = [];
                $update['status'] = AuthenticLog::AUTHENTIC_STATUS_PASS;
                $request_data['time']=date('Ymd H:i:s',time());
                $update['result'] = json_encode($request_data);
                AuthenticLog::where(['id'=>$log['id']])->update($update);
                //更新数据
                WechatMember::where(['id'=>$order_data['uid']])->update(['idcard_front'=>$log['idcard_front'],'idcard_back'=>$log['idcard_back'],'cert_name'=>$log['cert_name'],'cert_no'=>$log['cert_no']]);

                $update_data = [];
                $update_data['status'] = OrderService::ORDER_STATUS_SIGN_NOCHECK;
                if($type!='2') {
                    Order::where('id', $log['order_id'])->update($update_data);
                }
            }

            if($type=='2'){
                $order_id= $log['order_id'];
                if(!empty($order_id)){

                    $order = Order::from('sp_order_2 as o')
                        ->leftjoin('sp_member_2 as u','o.uid','u.id')
                        ->leftjoin('sp_order_goods_2 as og','o.id','og.order_id')
                        ->leftjoin('sp_goods_2 as g','g.id','og.goods_id')
                        ->where('o.id',$order_id)
                        ->select('o.id','o.uid','o.seller_id','o.flow_id','o.mobile','o.sign_num','o.user_email','o.address','o.trade_no'
                            ,'o.rent_total','o.month_total','o.amount','o.realname','o.rent_total','o.foregift'
                            ,'o.status','o.pay_type','u.esign_user_id','u.mobile as user_mobile','u.cert_name'
                            ,'u.cert_no','og.pact_type','og.is_buy_out','og.lease_price','og.goods_title','og.setmeal_title'
                            ,'og.lease_set','og.setmeal_price','og.goods_id','og.setmeal_id','og.spec_id'
                            ,'og.lease_price','og.lease_time','o.sign_url','o.prov','o.city','o.area','o.sign_status'
                            ,'o.prepayment_total','og.website_price','o.begin_time','o.end_time','g.new_grade','o.is_insurance_choose','o.is_insurance_choose_custom',
                            'og.setmeal_foregift')->first();
                    $order = $order ? $order->toArray() : [];
                    if(!empty($order)){
                        if($order['status'] != OrderService::ORDER_STATUS_SIGN_NOTPAY||$order['sign_status']==EsignService::ESIGN_STATUS_FINISH){
                            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'当前状态不能发起签署合同');
                        }

                        $member = WechatMember::where(['id'=>$this->member['id']])->select('esign_user_id','esign_seal_id','cert_name','cert_no')->first();
                        if(empty($member)||empty($member['esign_user_id'])||empty($member['esign_seal_id'])){
                            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '合同签署账号创建失败');
                        }


                        $order['pact_type'] = GoodsService::getGoodsPactName($order['pact_type']);
                        $order['isBuyout'] = $order['is_buy_out'];
                        $order['is_buy_out'] = GoodsService::getGoodsBuyoutName($order['is_buy_out']);

                        $order['first_rent']=OrderLease::where('order_id',$order_id)->where('which_period',1)->value('rent');
                        $shop_user = ShopUser::where('member_id',$order['seller_id'])->select('mechanism','company','faname','esign_shop_id','company_area','agreement','contact_tel','esign_seal_id','companyid')->first();
                        $shop_user = $shop_user ? $shop_user->toArray() : [];
                        //创建合同
                        $result = EsignV3Service::createFlowOneStepShopThree($order,$shop_user,$member);

                        if($result['status']==100){
                            return ReturnMsg(CommonService::HTTP_CODE_FAIL,$result['message']);
                        }else{
                            $res = Order::where('id',$order_id)->update(['sign_status'=>EsignService::ESIGN_STATUS_FINISH,'sign_url'=>$result['url'],'pact_url'=>$result['url']]);
                            if($res!==false){
                                $data['pdfUrl'] = $result['url'];
                                return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'合同发起成功',$data);
                            }else{
                                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '合同签署信息记录失败');
                            }
                        }

                    }else{
                        return ReturnMsg(CommonService::HTTP_CODE_FAIL, '订单不存在');
                    }
                }else{
                    return ReturnMsg(CommonService::HTTP_CODE_FAIL, '订单不存在');
                }
            }


            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'人脸认证成功',true);
        }else{
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'人脸认证失败',false);
        }


    }

    /**
     * 下单智能合同中转页面，获取用户实名认证信息
     */
    public function getAuthentic(Request $request){
        $order_id = $request->input('order_id');
        if(!empty($order_id)){
            $log = AuthenticLog::where(['order_id'=>$order_id])->select('cert_no','cert_name','status')->first();
            $log = obToArray($log);
            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'获取成功',$log);
        }else{
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '订单不存在');
        }

    }

    /**
     * 微信获取scheme链接
     */
    public function getSchemeUrl(Request $request){
        $input = $request->input();
        //获取微信小程序分享链接
        $res = WechatService::getSchemeUrl();

        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'获取成功',$res);

    }

}
